﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GPMS.Web.Controllers
{
    using GPMS.Model;
    using GPMS.Web.Helpers;
    using GPMS.BLL;
    /// <summary>
    /// 专业，后台管理
    /// </summary>
    public class SpecialtyController : BaseController
    {
        public ActionResult List()
        {
            return PartialView(gpmsDb.Specialties.Where(s=>s.IsDeleted==false).ToList());
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Specialty specialty)
        {
                if (ModelState.IsValid)
                {
                    if (SpecialtyHelper.IsExist(specialty.SpecialtyName,gpmsDb))
                    {

                        return JsonError("已存在同名专业");
                    }
                    else
                    {
                        specialty.SpecialtyID = Guid.NewGuid();
                        specialty.CreateDate = DateTime.Now;
                        gpmsDb.AddToSpecialties(specialty);
                        gpmsDb.SaveChanges();
                    }
                    return Success(null);
                }
                return JsonError(GetError(ModelState));
        }

        public ActionResult Edit(Guid id)
        {
            return View(gpmsDb.Specialties
                .Where(s => s.SpecialtyID == id)
                .FirstOrDefault());
        }

        [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            var specialty = SpecialtyHelper.Get(id, gpmsDb);
            try
            {
                UpdateModel(specialty, collection);
                gpmsDb.SaveChanges();
                return Success(null);
            }
            catch(Exception ex)
            {
                return JsonError("更新失败:"+ex.Message);
            }
        }

        public ActionResult Delete(Guid id)
        {
            return Confirm(string.Format("确定删除专业：{0} ?", 
                SpecialtyHelper.Get(id,gpmsDb).SpecialtyName));
        }

        [HttpPost]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            var userCount = (from u in gpmsDb.UserInfos
                             where u.SpecialtyID == id
                             select u).Count();
            if (userCount > 0)
            {
                return JsonError("该专业还有用户，不能删除");
            }
            else
            {
                var specialty = SpecialtyHelper.Get(id, gpmsDb);
                specialty.IsDeleted = true;
                gpmsDb.SaveChanges();
                return Success("删除成功");
            }
        }
    }
}
